﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Data.Sqlite;
using StackExchange.Profiling.Data;
using SP = StackExchange.Profiling;

namespace IceCS.MiniProfiler.Cmd
{
    public static class DBHelper
    {
        /// <summary>
        /// Returns an open connection that will have its queries profiled.
        /// </summary>
        /// <returns>the database connection abstraction</returns>
        public static DbConnection GetConnection()
        {
            //sqlite 的内存模式，即数据不会存储到磁盘上
            DbConnection conn = new SqliteConnection(_connectionString);

            // to get profiling times, we have to wrap whatever connection we're using in a ProfiledDbConnection
            // when MiniProfiler.Current is null, this connection will not record any database timings
            if (SP.MiniProfiler.Current != null)
            {
                conn = new ProfiledDbConnection(conn, SP.MiniProfiler.Current);
            }
            conn.Open();
            return conn;
        }

        private static string _connectionString = "Data Source=:memory:";

        public static void UseConnection(Action<DbConnection> action)
        {
            using (var connection =GetConnection())
            {
                action(connection);
            }
        }
    }
}
